package com.varian.security.handler;

import cn.hutool.extra.servlet.JakartaServletUtil;
import com.varian.log.util.LogUtil;
import com.varian.security.util.SecurityUtil;
import com.varian.tool.Func;
import com.varian.tool.contant.ResultConstant;
import com.varian.tool.result.IR;
import com.varian.tool.result.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.security.authorization.ExpressionAuthorizationDecision;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author ben
 * @since 2024/6/24
 */
@Slf4j
public class VarianAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (accessDeniedException instanceof AuthorizationDeniedException authorizationDeniedException && authorizationDeniedException.getAuthorizationResult() instanceof ExpressionAuthorizationDecision spelExpression) {
            log.warn("权限校验失败: {}", spelExpression.getExpression().getExpressionString());
        } else {
            log.warn("无权限: {}", accessDeniedException.getMessage());
        }
        IR result = R.result(ResultConstant.FORBIDDEN, ResultConstant.FAIL_CODE, accessDeniedException.getMessage());
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setStatus(result.getStatus());
        LogUtil.apiErrorLog(Func.getServletRequest(), accessDeniedException, result, SecurityUtil.getUserIdOnSafe());
        JakartaServletUtil.write(response, Func.jackson2JsonStr(result), MediaType.APPLICATION_JSON_VALUE);
    }
}
